package com.jsy.order.service.impl;

import com.jsy.common.constant.OrderConstant;
import com.jsy.common.vo.Result;
import com.jsy.goods.feign.SkuFeign;
import com.jsy.goods.feign.SpuFeign;
import com.jsy.goods.pojo.Sku;
import com.jsy.goods.pojo.Spu;
import com.jsy.order.dao.OrderItemMapper;
import com.jsy.order.pojo.OrderItem;
import com.jsy.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 将商品及购买数量加入到当前登录用户对应的购物车中
     *
     * @param id       商品sku id
     * @param num      购买数量
     * @param username 登录用户
     */
    @Override
    public void add(String id, Integer num, String username) {
        //根据sku id查询sku
        Result<Sku> skuResult = skuFeign.findById(id);
        if (skuResult.getData() != null) {
            //根据sku id查询spu
            Result<Spu> spuResult = spuFeign.findById(skuResult.getData().getSpuId());
            //根据sku和spu及购买数量构造orderItem
            OrderItem orderItem = createOrderItem(skuResult.getData(), spuResult.getData(), num);
            //将orderItem存入redis
            redisTemplate.boundHashOps(OrderConstant.CART_PREFIX + username).put(id, orderItem);
        }
    }

    @Override
    public List<OrderItem> list(String username) {

        return redisTemplate.boundHashOps(OrderConstant.CART_PREFIX+username).values();
    }

    /**
     * 构造orderItem
     *
     * @param sku 商品sku
     * @param spu 商品spu
     * @param num 购买数量
     * @return orderItem
     */
    private OrderItem createOrderItem(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem = new OrderItem();
        orderItem.setSpuId(spu.getId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());
        orderItem.setImage(sku.getImage());
        orderItem.setIsReturn("0");
        orderItem.setNum(num);
        orderItem.setPrice(sku.getPrice());//单价

        //价格=单个sku的价格*购买数量、支付金额
        orderItem.setMoney(sku.getPrice() * num);
        orderItem.setPayMoney(orderItem.getMoney());
        //重量=单个sku的重量*购买数量
        orderItem.setWeight(sku.getWeight() * num);
        //三级分类
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());

        return orderItem;
    }
}
